package com.jianshuge.app.ui;

import java.io.File;
import java.util.List;

import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;

import com.jianshuge.app.bean.DoubanBook;
import com.jianshuge.app.bean.MyBookDetail;
import com.jianshuge.app.bean.MyBookDetail.doubanComment;
import com.jianshuge.app.bean.MyResult;

import com.jianshuge.app.common.FileUtils;
import com.jianshuge.app.common.StringUtils;

import com.jianshuge.app.common.UIHelper;
import com.jianshuge.app.widget.LinkView;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

public class BookDetail extends BaseActivity {
	private ImageView mBack;
	private ImageView mRefresh;
	private ProgressBar mProgressbar;
	
	private LinearLayout mLinearlayout;
	private String douban_subject_id = null;

	private Handler mHandler;
	private Handler mdoubanHandler;

	public ImageView book_image;  
	private TextView book_title;
	private TextView book_author;
	private TextView book_rating;
	private TextView book_pubdate;
	private TextView book_publisher;
	private TextView book_isbn;
	private TextView book_summary;
	private ProgressBar mDoubanTopProgress;

	private	 LinearLayout doubanComments;
	private LayoutInflater 	listContainer;		//视图容器

    private Handler mBookHandler;
    
	private RadioButton mShareBook;
	private RadioButton mFavoriteBook;
	private ProgressDialog mMyProgress;

    private int cur_book_id;
    MyBookDetail my_book_detail = null;
    
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.book_detail);
		
		
		douban_subject_id = getIntent().getStringExtra("subject_id");
		cur_book_id = getIntent().getIntExtra("book_id", 0);

    	mProgressbar = (ProgressBar)findViewById(R.id.book_detail_head_progress);
    	mBack = (ImageView)findViewById(R.id.book_detail_back);
    	mRefresh = (ImageView)findViewById(R.id.book_detail_refresh);
    	
    	mLinearlayout = (LinearLayout)findViewById(R.id.book_detail_linearlayout);
     	
    	mBack.setOnClickListener(UIHelper.finish(this));
    	mRefresh.setOnClickListener(refreshClickListener);  

		book_image = (ImageView)findViewById(R.id.book_detail_image);
		book_title = (TextView)findViewById(R.id.book_detail_title);
		book_author = (TextView)findViewById(R.id.book_detail_author);
		book_publisher = (TextView)findViewById(R.id.book_detail_publisher);
		book_pubdate = (TextView)findViewById(R.id.book_detail_pubdate);
		book_isbn = (TextView)findViewById(R.id.book_detail_isbn);
		book_rating = (TextView)findViewById(R.id.book_detail_douban_rating);
		book_summary = (TextView)findViewById(R.id.book_detail_intro);
		
		mDoubanTopProgress   = (ProgressBar)findViewById(R.id.douban_topbar_progress);
		mDoubanTopProgress.setVisibility(View.GONE);
		

		mShareBook	= (RadioButton)findViewById(R.id.book_detail_footbar_share);
		mShareBook.setOnClickListener(shareClickListener);
		mFavoriteBook	= (RadioButton)findViewById(R.id.book_detail_footbar_favorite);
		mFavoriteBook.setOnClickListener(favoriteClickListener);
		
		doubanComments	= (LinearLayout)findViewById(R.id.book_detail_douban_comments_container);
		listContainer = LayoutInflater.from(this);
	
		mBookHandler = new Handler() {
	
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE, 1);
				if (msg.what == 1 && msg.obj != null) {
					my_book_detail = (MyBookDetail) msg.obj;
					
					String book_image_url = my_book_detail.getImageUrl();
					if(book_image_url.endsWith("portrait.gif") || StringUtils.isEmpty(book_image_url)){
						book_image.setImageResource(R.drawable.default_book_pic);
					}else{
						UIHelper.showUserFace(book_image, book_image_url);
					}

					book_title.setText("书名： " +  my_book_detail.getTitle());
					book_author.setText("作者： " + my_book_detail.getAuthor());
					book_publisher.setText("出版社： " + my_book_detail.getPublisher());
					book_pubdate.setText("出版日期：" + my_book_detail.getPubdate());
					book_isbn.setText("ISBN： " + my_book_detail.getIsbn());
					book_rating.setText("豆瓣评分： " + my_book_detail.getRating());
					
					book_summary.setText("" + my_book_detail.getSummary());
					
					doubanComments.setVisibility(View.GONE);
					doubanComments.removeAllViews();//先清空
					
					List<doubanComment> comments = my_book_detail.getDoubanComments();
					if( comments.size() > 0){
						for(doubanComment comment : comments ){
							
							View view = listContainer.inflate(R.layout.book_detail_douban_comment_listitem, null);
						    ImageView face = (ImageView)view.findViewById(R.id.douban_comment_userface);
						    TextView name = (TextView)view.findViewById(R.id.douban_comment_username);		
						    TextView title = (TextView)view.findViewById(R.id.douban_comment_title);
						    LinkView content = (LinkView)view.findViewById(R.id.douban_comment_content);
						    
							String faceURL = comment.author_image;
							if(faceURL.endsWith("portrait.gif") || StringUtils.isEmpty(faceURL)){
								face.setImageResource(R.drawable.widget_dface);
							}else{
								UIHelper.showUserFace(face, faceURL);
							}
							
							name.setText(comment.author);
							
							title.setTag(comment);
							title.setText(comment.title);							
							content.setLinkText(comment.summary);

							view.setTag(comment);
							view.setOnClickListener( doubanClickListener );
							
							doubanComments.addView(view);
						}
						doubanComments.setVisibility(View.VISIBLE);
					}
					
					douban_subject_id = my_book_detail.getSubjectId();
					
					if (my_book_detail.getFavoriteStatus() == true) {
						mFavoriteBook.setText("已收藏");
					} else {	
						mFavoriteBook.setText("收藏");
					}

					
				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(BookDetail.this);
				}
				mProgressbar.setVisibility(View.GONE);
			}
		};
		
		mdoubanHandler = new Handler() {
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE, 1);
				
				if (msg.what == 1) {
					MyResult res = (MyResult) msg.obj;
					if (res.OK()) {
						cur_book_id = Integer.parseInt(res.getExtraCode());
						loadBookDetail(cur_book_id, mBookHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
					}
				} else {					
					((AppException) msg.obj).makeToast(BookDetail.this);
				}
			}
		};
		
		
		mHandler = new Handler() {
			
			public void handleMessage(Message msg) {
				
				if (msg.what == 1 && msg.obj != null) {
					DoubanBook doubanbook = (DoubanBook) msg.obj;
					douban_subject_id = doubanbook.getSubjectId();
					saveDoubanBookThread(douban_subject_id, mdoubanHandler, true);
					
				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(BookDetail.this);
				}
			}
		};
		
		if( douban_subject_id != null )
			loadDoubanBookThread(douban_subject_id, mHandler, true);
		else
			loadBookDetail(cur_book_id, mBookHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
		
	}
	
	
	private void loadDoubanBookThread(final String subject_id, final Handler handler, final boolean isRefresh){ 

		this.headButtonSwitch(DATA_LOAD_ING, 1);
		new Thread(){
			public void run() {
				
				Message msg = new Message();				
				try {
					
					DoubanBook doubanbook = ((AppContext)getApplication()).getDoubanBookBySubject(subject_id, isRefresh);
					msg.what = 1;
					msg.obj = doubanbook;
	            
				} catch (AppException e) {
					
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            
				}
				
                handler.sendMessage(msg);
			}
			
		}.start();
	}
	
	private void  saveDoubanBookThread(final String subject_id, final Handler handler, final boolean isRefresh){  

		new Thread(){
			public void run() {
				Message msg = new Message();
				try {
					
					MyResult res = ((AppContext)getApplication()).saveDoubanBook(subject_id, isRefresh);
					msg.what = 1;
					msg.obj = res;
				} catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
				}	
				handler.sendMessage(msg);
			}
			
		}.start();
		
	}

	
    /**
     * 头部加载展示
     * @param type
     * @param action 1-init 2-refresh
     */

    private void headButtonSwitch(int type,int action) {
    	switch (type) {
		case DATA_LOAD_ING:
			if(action==1)mLinearlayout.setVisibility(View.GONE);
			mProgressbar.setVisibility(View.VISIBLE);
			mRefresh.setVisibility(View.GONE);
			break;
		case DATA_LOAD_COMPLETE:
			mLinearlayout.setVisibility(View.VISIBLE);
			mProgressbar.setVisibility(View.GONE);
			mRefresh.setVisibility(View.VISIBLE);
			break;
		}
    }
	
	private void loadBookDetail(final int book_id, final Handler handler, final int action){  
		
		this.headButtonSwitch(DATA_LOAD_ING, 1);
		
		new Thread(){
			
			public void run() {
				
				Message msg = new Message();	
				
				boolean isRefresh = false;
				if(action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;

				try {
					MyBookDetail my_book_detail = ((AppContext)getApplication()).getBookDetail(book_id, isRefresh);
					msg.what = 1;
					msg.obj = my_book_detail;
				} catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e; 
				}
				
                handler.sendMessage(msg);
			}
			
		}.start();
		
	}
	
	private View.OnClickListener favoriteClickListener = new View.OnClickListener(){
		
		public void onClick(View v) {
			
			mMyProgress = ProgressDialog.show(v.getContext(), null, "加载中···",true,true); 
		
			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					
					if(mMyProgress!=null)
						mMyProgress.dismiss();
					
					if (msg.what == 1) {
						MyResult res = (MyResult) msg.obj;
						if (res.OK()) {
							
							if (my_book_detail.getFavoriteStatus() == true) {
								my_book_detail.setFavoriteStatus(false);
								mFavoriteBook.setText("收藏");
							} else {	
								my_book_detail.setFavoriteStatus(true);
								mFavoriteBook.setText("已收藏");
							}
							UIHelper.ToastMessage(BookDetail.this, res.getErrorMessage());
						}
					
					} else {					
						((AppException) msg.obj).makeToast(BookDetail.this);
					}
				}
			};
			
			new Thread() {
				public void run() {
					Message msg = new Message();
					MyResult res = null;
					try {	
						AppContext ac = (AppContext)getApplication();
						final int uid = ac.getLoginUid();
						res = ac.addFavorite(uid, cur_book_id);
						
						if (my_book_detail.getFavoriteStatus() == true) {
							res = ac.delFavorite(uid, cur_book_id);
						} else {
							res = ac.addFavorite(uid, cur_book_id);
						}
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}
					handler.sendMessage(msg);
				}
			}.start();
		}
	};


    private View.OnClickListener refreshClickListener = new View.OnClickListener() {
		public void onClick(View v) {	
			loadBookDetail(cur_book_id, mBookHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
		}
	};
	
	
	private View.OnClickListener doubanClickListener = new View.OnClickListener(){
		public void onClick(View v) {
			
			doubanComment comment = null;
			
    		//判断是否是TextView
    		if (v instanceof TextView) {
    			comment = (doubanComment)v.getTag();
			} else {
				TextView tv = (TextView) v.findViewById(R.id.douban_comment_title);
				comment = (doubanComment) tv.getTag();
			}
    		
			if (comment == null)
				return;
			
			UIHelper.showDoubanCommentDetail(v.getContext(), comment.title, comment.comment_uri);
		}
	};
	
	private View.OnClickListener shareClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			
			String share_title = "荐书阁 好书推荐：" + my_book_detail.getTitle() + "（分享自 @荐书阁）";
			String share_url = "http://jianshuge.com/book/show/" + cur_book_id + ".html";
	
			String share_img_url = my_book_detail.getImageUrl();
			final String filename = FileUtils.getFileName(share_img_url);
			String filepath = v.getContext().getFilesDir() + File.separator + filename;		
			if( FileUtils.checkFilePathExists(filepath) )
				UIHelper.showShareDialog(BookDetail.this, share_title, share_url, filepath);
			else
				UIHelper.showShareDialog(BookDetail.this, share_title, share_url, null);
			
		}
	};
}
